package core;

import lombok.SneakyThrows;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.FileWriter;
import java.util.Properties;

public class CodeGeneration {
    static {
        Properties prop = new Properties();
        prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        Velocity.init(prop);
    }

    /**
     * @param data         填充到模板的数据
     * @param templateName 模板名字 -> 默认在 /resources/vms 目录下
     * @param filename     生成文件名字 -> 默认在 /resources/out 目录下
     */
    @SneakyThrows
    public static void createSourceCode(Object data, String templateName, String filename) {
        VelocityContext context = new VelocityContext();
        context.put("data", data);
        Template tpl = Velocity.getTemplate("vms/" + templateName, "UTF-8");
        String path = System.getProperty("user.dir").replaceAll("\\\\", "/") + "/CTypesCodeGeneration/src/main/resources/out/";
        FileWriter fw = new FileWriter(path + filename);
        tpl.merge(context, fw);
        fw.close();
    }
}


